package user

import (
	"gitee.com/go-mao/mao/frame"
	"gitee.com/go-mao/mao/libs/try"
)

type userDomain struct {
	*Component
}

func (this *Component) UserDomain() *userDomain {
	return &userDomain{this}
}

// 创建用户
func (this *userDomain) Create(username string) *User {
	userEntity := this.NewUser()
	userEntity.Username = username
	if !userEntity.Create() {
		try.Throw(frame.CODE_SQL, "用户创建失败")
	}
	return userEntity
}

// 创建用户
func (this *userDomain) Get(id int64) (*User, bool) {
	userEntity := this.NewUser()
	exists := userEntity.Match("Id", id).Get()
	return userEntity, exists
}

// 创建用户
func (this *userDomain) Update(id int64, username string) {
	userEntity, exists := this.Get(id)
	if !exists {
		try.Throw(frame.CODE_SQL, "找不到该用户")
	}
	userEntity.Username = username
	if !userEntity.Update() {
		try.Throw(frame.CODE_SQL, "用户修改失败")
	}
}

// 删除用户
func (this *userDomain) Remove(id int64) {
	userEntity, exists := this.Get(id)
	if !exists {
		try.Throw(frame.CODE_SQL, "找不到该用户")
	}
	if !userEntity.Delete() {
		try.Throw(frame.CODE_SQL, "用户删除失败")
	}
}

// 用户查询
func (this *userDomain) Find(username string, listPtr any, page, limit int) int64 {
	db := this.OrmTable(this.NewUser())
	if username != "" {
		db.Where("`Username`=?", username)
	}
	db.Desc("Id")
	return this.FindPage(db, listPtr, page, limit)
}
